package readutils;

my $dbname = "position_mark.db";

sub init_position{
    # my $dbname = "position_mark.db";
    open(FDB,">",$dbname) or die "can not create $dbname\n";
    print FDB "0";
    close(FDB);
}

sub read_with_position {
    my $filename = shift;
    my $how_many_lines_read = shift;
    print "-----------------------------------\n";
    if (not (-e $dbname)) {
        print "${dbname} not exist\n";
        &init_position();
        print "${dbname} created.INIT POSITION 0\n"
    }
    my @text = &read_at_position($filename,$how_many_lines_read);
    return @text;
}

sub loader_read_position {
    # my $dbname = "position_mark.db";
    open(FDB,"<",$dbname) or die "can not open ${dbname}\n";
    $position = <FDB>;
    close(FDB);
    return $position;
}
sub set_file_position {
    my $position = shift;
    # my $dbname = "position_mark.db";
    open(FDB,">",$dbname) or die "can not open $dbname\n";
    print FDB $position;
    close(FDB);
}
sub read_at_position {
    my $filename = shift;
    my $how_many_lines_want_read = shift;
    my $p = &loader_read_position();
    print "start read position is $p\n";
    my @lines;
    open (FNAME,"<",$filename) or die "can not open $filename\n";
    seek(FNAME,$p,0);
    for (my $i = 0; $i < $how_many_lines_want_read; $i++) {
        my $text = readline(FNAME);
        last if not(defined($text)); #judge eof undef or '0'; $text is '0' return false
        push @lines,$text;
    }
    $p = tell(FNAME);
    print "end read position is $p\n";
    &set_file_position($p);
    close(FNAME);
    print "read over\n------------------------------\n";
    return @lines;
}

1;